package view;

import java.awt.BorderLayout;
import java.awt.Color;
 
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.border.Border;
import model.*;
import view.Grid;
import view.RunThread;
 
public class View extends JFrame {

	Space2D universe;
	Grid grid;
	boolean isRunning = false;
	RunThread runner;
	int nbStep;
	
	//South Components
	JPanel southPanel;
	JButton southRunButton;
	JButton southStopButton;
	JSlider southSlider;
	JLabel southNbStepLabel;
	
	//NorthComponents
	JPanel northPanel;
	JLabel northGridSizeLabel;
	JLabel northXSizeLabel;
	JLabel northYLabel;
	JTextField northXTextField;
	JTextField northYTextField;
	JButton northCreateGridButton;
	
	//WestComponents
	JPanel westPanel;
	JLabel westAntLabel;
	JLabel westXAntLabel;
	JLabel westYAntLabel;
	JTextField westXAntTextField;
	JTextField westYAntTextField;
	JButton westAddAntButton;
	
	public View() throws Exception{

		this.setTitle("View");
		this.setSize(400, 500);
		this.setLocationRelativeTo(null);  
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		this.setLayout(new BorderLayout());
		
		//this.initGrid();
		this.initButton();

		//this.getContentPane().add(new JButton("CENTER"), BorderLayout.NORTH);
		//this.getContentPane().add(grid, BorderLayout.CENTER);
		
		//The South
		initSouthPanel();
		//The North
		initNorthPanel();
		//The West
		initWestPanel();
		
		//this.getContentPane().add(new JButton("WEST"), BorderLayout.WEST);
		//this.getContentPane().add(new JButton("EAST"), BorderLayout.EAST);

		this.setVisible(true);
	}
	
	public void initGrid() throws Exception{
		Space2D universe = new Space2D(50, 50);
		Point p1 = new Point(0,0);
		Point p2 = new Point(7,3);
		Point p3 = new Point(4,5);
		Point p4 = new Point(7,9);
		
		Point p5 = new Point(2,2);
		
		for (int i=0; i<universe.getDimY();i++){
			if (i%4 == 0){
				for (int j=0; j<universe.getDimX();j++){
					if (j%4 == 0){
						Resource r = null;
						Point pr = new Point(i, j);
						
						if (j%12 == 0){
							r = new Resource(universe, pr, "r1");
						} else if (j%12 == 4){
							r = new Resource(universe, pr, "r2");
						} else if (j%12 == 8){
							r = new Resource(universe, pr, "r3");
						}
						if (r != null){
							universe.addResource(r);
						}
						}
						Ant ant = null;
						Point pant = new Point(i, j);
						if ((j%13 == 5)&&(i%12 == 0)){
							ant = new Ant(universe, pant);
						}
						if (ant != null){
							universe.addAnt(ant);
						}
					}
				}
			}
		
		this.grid = new Grid(universe, false);
		this.universe = universe;
	}
	
	public void initButton(){
		
		//southRunButton
		this.southRunButton = new JButton("Run");
        this.southRunButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					southRunButtonActionPerformed(evt);
				} catch (Exception ex) {
					Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
				}
            }
        });
		
		//southStopButton
		this.southStopButton = new JButton("Stop");
        this.southStopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					southStopButtonActionPerformed(evt);
				} catch (Exception ex) {
					Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
				}
            }
        });
		
		//northCreateGridButton
		this.northCreateGridButton = new JButton("Creer la grille");
        this.northCreateGridButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					northCreateGridButtonActionPerformed(evt);
				} catch (Exception ex) {
					Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
				}
            }
        });
		
		//westAddAntButton
		this.westAddAntButton = new JButton("Ajouter la fourmi");
        this.westAddAntButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
				try {
					westAddAntButtonActionPerformed(evt);
				} catch (Exception ex) {
					Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
				}
            }
        });
	}
	
	public void initSouthPanel(){
		this.southPanel  = new JPanel();
		this.southSlider = new JSlider(0, 1000, 500);
		
		this.southSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                southSliderStateChanged(evt);
            }
        });
		
		southPanel.add(southSlider);
		
		southNbStepLabel = new JLabel("Nombre d'etapes : 0");
		southPanel.add(southNbStepLabel);
		southPanel.add(southRunButton);
		southPanel.add(southStopButton);
		this.getContentPane().add(southPanel, BorderLayout.SOUTH);
	}
	
	public void initNorthPanel(){
		northPanel = new JPanel();
		
		this.northGridSizeLabel = new JLabel("Taille de la grille - ");
		this.northXSizeLabel = new JLabel("X :");
		this.northYLabel = new JLabel("Y :");
		this.northXTextField = new JTextField("  50");
		this.northYTextField = new JTextField("  50");
		
		this.northPanel.add(this.northGridSizeLabel);
		this.northPanel.add(this.northXSizeLabel);
		this.northPanel.add(this.northXTextField);
		this.northPanel.add(this.northYLabel);
		this.northPanel.add(this.northYTextField);
		this.northPanel.add(this.northCreateGridButton);
	 
		this.getContentPane().add(northPanel, BorderLayout.NORTH);
	}
	
	public void initWestPanel(){
		westPanel = new JPanel();
		westPanel.setLayout(new BoxLayout(westPanel, BoxLayout.Y_AXIS));
		
		JPanel fourmiPanel = new JPanel();
		//Border fourmiBorder = new Border();
		//fourmiPanel.setBorder(border);
		this.westAntLabel = new JLabel("Fourmi - ");
		this.westXAntLabel = new JLabel("X :");
		this.westYAntLabel = new JLabel("Y :");
		this.westXAntTextField = new JTextField("   0");
		this.westYAntTextField = new JTextField("   0");
		
		westPanel.add(this.westAntLabel);
		westPanel.add(this.westXAntLabel);
		westPanel.add(this.westXAntTextField);
		westPanel.add(this.westYAntLabel);
		westPanel.add(this.westYAntTextField);
		westPanel.add(this.westAddAntButton);
		
		/*
		this.westPanel.add(this.westAntLabel);
		this.westPanel.add(this.westXAntLabel);
		this.westPanel.add(this.westXAntTextField);
		this.westPanel.add(this.westYAntLabel);
		this.westPanel.add(this.westYAntTextField);
		this.westPanel.add(this.westAddAntButton);
		*/
	 
		this.getContentPane().add(westPanel, BorderLayout.WEST);
	}
	
	private void southSliderStateChanged(javax.swing.event.ChangeEvent evt) {
		int tsleep = this.southSlider.getValue();
		runner.setTSleep(tsleep);
		
	}
	
	private void southRunButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception {
		if ((this.grid!=null)&&(!isRunning)){
			runner = new RunThread(this.grid, this.universe, this.southSlider.getValue(), this.nbStep, this.southNbStepLabel);
			runner.start();
			isRunning = true;
		}
	}
	
	private void southStopButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception {
		if (isRunning){
			this.nbStep = runner.kill();
			isRunning = false;
		}
	}
	
	private void northCreateGridButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception {
		if (this.isRunning){
			runner.kill();
		}
		String xString = this.northXTextField.getText().replaceAll(" ", "");
		String yString = this.northYTextField.getText().replaceAll(" ", "");
		
		if (!this.isInteger(xString)){
			JOptionPane.showMessageDialog(null, "X doit etre un entier");
		} else if (!this.isInteger(yString)){
			JOptionPane.showMessageDialog(null, "Y doit etre un entier");
		} else {
			Integer x = Integer.parseInt(xString);
			Integer y = Integer.parseInt(yString);
			universe = new Space2D(x, y);
			this.grid = new Grid(universe, false);
			System.out.print("Grid cree de taille : "+x+":"+y);
			this.getContentPane().add(grid, BorderLayout.CENTER);
		}
			
	}
	
	private void westAddAntButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception {
		
		if (this.grid == null){
			JOptionPane.showMessageDialog(null, "Vous n'avez pas encore cree de grille");
			return;
		}
		
		boolean reRun = false;
		if (this.isRunning){
			this.nbStep = runner.kill();
			isRunning = false;
			reRun = true;
		}
		
		String xString = this.westXAntTextField.getText().replaceAll(" ", "");
		String yString = this.westYAntTextField.getText().replaceAll(" ", "");
		
		if (!this.isInteger(xString)){
			JOptionPane.showMessageDialog(null, "X doit etre un entier");
		} else if (!this.isInteger(yString)){
			JOptionPane.showMessageDialog(null, "Y doit etre un entier");
		} else {
			Integer x = Integer.parseInt(xString);
			if (x >= this.universe.getDimX()){
				JOptionPane.showMessageDialog(null, "X est superieur a la taille de la grille");
				return;
			}
			Integer y = Integer.parseInt(yString);
			if (y >= this.universe.getDimY()){
				JOptionPane.showMessageDialog(null, "Y est superieur a la taille de la grille");
				return;
			}
			Point loc = new Point(x,y);
			Cell cell = this.universe.getCell(loc);
			if (cell!=null){
				if (!cell.containsAnt()){
					Ant ant = new Ant(this.universe, loc);
					this.universe.addAnt(ant);
					System.out.print("Ant ajoute a : "+x+"-"+y);
				} else {
					JOptionPane.showMessageDialog(null, "Une fourmi se trouve deja ici");
					return;
				}
			} else {
				Ant ant = new Ant(this.universe, loc);
				this.universe.addAnt(ant);
				System.out.print("Ant ajoute a : "+x+"-"+y);
			}	
		}
		
		if (reRun){
			runner = new RunThread(this.grid, this.universe, this.southSlider.getValue(), this.nbStep, this.southNbStepLabel);
			runner.start();
			isRunning = true;
		}
			
	}
	
	// Test si le string represente un nombre
    public boolean isInteger(String chaine) {
		try {
			Integer.parseInt(chaine);
		} catch (NumberFormatException e){
			return false;
		}
		return true;
	}
	
	public static void main(String[] args) throws Exception{
        
		View view = new View();
	} 
}

